<?php
/**
 * 疯狂夺金模块微站定义
 *
 * @author junsion
 * @url http://s.we7.cc/index.php?c=store&a=author&uid=74516
 */
defined('IN_IA') or exit('Access Denied');
define('RES','../addons/junsion_getscore/template/');
class Junsion_getscoreModuleSite extends WeModuleSite {

	public function doMobileCover() {
		//这个操作被定义用来呈现 功能封面
		global $_W,$_GPC;
		$mem = $this->getMem();
		$cfg = $this->module['config'];
		$cates = $cfg['cates'];
		$cid = intval($_GPC['cid']);
		$cate = $cates[$cid];
		$code = explode(',',$cate['codes']);
		foreach ($code as $value) {
			$codes[] = array('val'=>$value,'code'=>$value/$cfg['creditnum']);
		}
		
		//先查询当前分场第几期和什么题目
		$round = get("select * from ".tb('round')." where weid='{$_W['uniacid']}' and type='{$cid}'");
		if (empty($round)){//第一次开始
			$question = get("select * from ".tb('question')." where type='{$cid}' and weid='{$_W['uniacid']}' and isdel=0 and status=1  order by id limit 1");
			insert('round',array('weid'=>$_W['uniacid'],'type'=>$cid,'qid'=>$question['id'],'round'=>1,'start'=>time()));
			$curRound = 1;
		}else{//已经开始了
			$question = get("select * from ".tb('question')." where id='{$round['qid']}'");
			$curRound = $round['round'];
		}
		
		$record = getall("select award,sel from ".tb('record')." where qid='{$question['id']}' and round='{$curRound}'");
		$had = 0;
		$yes = 0;
		$no = 0; 
		foreach ($record as $value) {
			$had += $value['award'];
			if (!$value['sel']) $yes++;
			else $no++;
		}
		if ($yes > 0) $yes = intval(floatval($yes/($yes+$no)) * 100);
		if ($no > 0) $no = 100 - $yes;
		$last = $cate['credit'] - $had;
		
		if ($curRound > 1){
			//上期数据
			$his = get("select mid,code from ".tb('award')." where weid='{$_W['uniacid']}' and type='{$cid}' and round='".($curRound-1)."'");
			$hm = get("select nickname,avatar from ".tb('mem')." where id='{$his['mid']}'");
			$his['nickname'] = $hm['nickname'];
			$his['avatar'] = $hm['avatar'];
		}
		include $this->template('cover');
	}
	
	public function doMobileMsg(){
		global $_W,$_GPC;
		$cfg = $this->module['config'];
		$cid = intval($_GPC['cid']);
		$list = getall("select mid,award,round from ".tb('award')." where type='{$cid}' order by round desc limit 10");
		if ($list){
			foreach ($list as $value) {
				$mids[] = $value['mid'];
			}
			if ($mids){
				$ms = getall("select nickname,id from ".tb('mem')." where id in (".implode(',', $mids).")",'id');
			}
			
			foreach ($list as &$v) {
				$msg[] = "恭喜".$ms[$v['mid']]['nickname']."在".$cfg['cates'][$cid]['title']."{$v['round']}期中奖{$v['award']}{$cfg['creditname']}";
			}
			resp($msg);
		}else die('1');
	}
	
	public function doMobileTask(){
		global $_W,$_GPC;
		$mem = $this->getMem();
		$cid = intval($_GPC['cid']);
		$now = time();
		$list = getall("select * from ".tb('task')." where starttime<=$now and endtime >$now and status=1 order by sort desc");
		if ($list){
			$tasks = array();
			foreach ($list as &$v) {
				$task = array('logo'=>toimage($v['logo']),'type'=>$v['type'],'des'=>$v['des'],'title'=>$v['title'],'tid'=>$v['id']);
				if ($v['type'] != 5){
					if ($v['timetype']){//时间段任务  查询该时间段是否有完成的任务
						$con = " and createtime<={$v['endtime']} and createtime>={$v['starttime']}";
					}else {//每日任务
						$con = " and to_days(from_unixtime(createtime))=to_days(now())";
					}
					$r = getall("select level from ".tb('task_record')." where mid='{$mem['id']}' and tid='{$v['id']}' $con");
					$a = unserialize($v['award']);
					if ($r){
						if ($v['type'] == 1) continue;
						elseif ($v['type'] == 2 || $v['type'] == 3){//若是夺金或连胜任务
							$l = 0;
							foreach ($r as $val) {
								$l = max($l,$val['level']);
							}
							if (count($r) == count($a)){//任务全完成了
								continue;
							}else{
								if ($v['type'] == 2) $num = intval(col("select count(1) from ".tb('record')." where mid='{$mem['id']}' {$con}"));
								elseif ($v['type'] == 3) $num = intval(col("select count(1) from ".tb('award')." where mid='{$mem['id']}' {$con}"));
								$task['des'] = $a[$l+1]['desc']."<br>({$num}/".$a[$l+1]['key'].")";
							}
						}else{
							foreach ($r as $value) {
								$ls[] = $value['level'];
							}
							foreach ($a as $val) {
								if (!in_array($val['key'], $ls)) $cids[] = $val['key']; //该任务没领过的
							}
							if ($cids){
								foreach ($a as $value) {
									if ($value['key'] == $cids[0]){//未玩过这场
										$task['des'] = $value['desc'];
										break;
									}
								}
							}else continue;
						}
					}elseif ($v['type'] > 1){
						$more = '';
						if ($v['type'] == 2 || $v['type'] == 3){
							if ($v['type'] == 2) $num = intval(col("select count(1) from ".tb('record')." where mid='{$mem['id']}' {$con}"));
							elseif ($v['type'] == 3) $num = intval(col("select count(1) from ".tb('award')." where mid='{$mem['id']}' {$con}"));
							$more = "<br>({$num}/".$a[0]['key'].")";
						}
						$task['des'] = $a[0]['desc'].$more;
					}
				}else $task['url'] = $v['award'];
				$tasks[] = $task;
			}
			resp($tasks);
		}else die('1');
	}
	
	public function doMobileData(){
		global $_W,$_GPC;
		$mem = $this->getMem();
		$cates = $this->module['config']['cates'];
		$list = getall("select * from ".tb('record')." where mid='{$mem['id']}' and createtime>=".(time()-5*24*3600));
		if ($list){
			foreach ($list as $value) {
				if ($str) $str .= " or ";
				$str .= " type='{$value['type']}' and round='{$value['round']}'";
			}
			if ($str){
				$award = getall("select code,type,round from ".tb('award')." where mid='{$mem['id']}' and {$str}");
				foreach ($award as $value) {
					$als[$value['type'].'-'.$value['round']] = $value['code'];
				}
			}
			
			foreach ($list as $value) {
				$codes = explode(',', $value['codes']);
				$code = $als[$value['type'].'-'.$value['round']];
				$record[date('Ymd',$value['createtime'])][] = array(
						'cate'=>$cates[$value['type']]['title'],
						'round'=>$value['round'],
						'codes'=>$codes,
						'count'=>count($codes),
						'code'=>$code,
						'status'=>in_array($code, $codes),
				);
			}
		}
		include $this->template('record');
	}
	
	public function doMobileRecord(){
		global $_W,$_GPC;
		$page = intval($_GPC['page']);
		$qid = intval($_GPC['qid']);
		$round = intval($_GPC['round']);
		$list = getall("select mid,createtime,award,msecond from ".tb('record')." where qid='{$qid}' and round='{$round}' order by createtime desc,msecond desc limit ".(($page-1)*10).",10");
		if ($list){
			foreach ($list as $value) {
				$mids[] = $value['mid'];
			}
			if ($mids){
				$ms = getall("select nickname,avatar,id from ".tb('mem')." where id in (".implode(',', $mids).")",'id');
			}
			foreach ($list as &$v) {
				$v['nickname'] = $ms[$v['mid']]['nickname'];
				$v['avatar'] = $ms[$v['mid']]['avatar'];
				$v['createtime'] = date('Y-m-d H:i:s',$v['createtime']).".".sprintf('%06d',$v['msecond']);
			}
			resp($list);
		}else die('1');
	}
	
	public function doMobileLog(){
		global $_W,$_GPC;
		$cates = $this->module['config']['cates'];
		$page = max(1,$_GPC['page']);
		$cid = intval($_GPC['cid']);
		$cate = $cates[$cid];
		$list = getall("select * from ".tb('award')." where weid='{$_W['uniacid']}' and type='{$cid}' order by round desc limit ".(($page-1)*10).",10");
		if ($list){
			foreach ($list as $value) {
				$mids[] = $value['mid'];
			}
			if ($mids){
				$ms = getall("select nickname,avatar,id from ".tb('mem')." where id in (".implode(',', $mids).")",'id');
			}
			foreach ($list as &$v) {
				$v['nickname'] = $ms[$v['mid']]['nickname'];
				$v['avatar'] = $ms[$v['mid']]['avatar'];
			}
			if ($_W['isajax']) resp($list);
		}elseif ($_W['isajax']) die('1');
		include $this->template('log');
	}
	
	public function doMobileVote(){
		global $_W,$_GPC;
		$mem = $this->getMem();
		$cfg = $this->module['config'];
		$round = intval($_GPC['round']);
		$type = intval($_GPC['type']);
		$cid = intval($_GPC['cid']);
		$amount = intval($_GPC['amount']);
		
		if ($mem['credit'] < $amount){
			resp(array('code'=>4,'msg'=>'你的'.$cfg['creditname'].'不足！'));
		}
		$curRound = get("select qid,round,start from ".tb('round')." where weid='{$_W['uniacid']}' and type='{$cid}'");
		if ($curRound['round'] != $round){//过期了
			resp(array('code'=>2));
		}
		$qid = $curRound['qid'];
		$question = get('select * from '.tb('question')." where id='{$qid}'");
		$cate = $cfg['cates'][$cid];
		$codes = $cate['codes'];
		$codes = explode(',',$codes);
		if (!in_array($amount, $codes)){
			resp(array('code'=>0,'msg'=>'数值有误！'));
		}
		//记录下单记录
		//获取最大的夺金码先
		$max = 0;
		$rcodes = col("select codes from ".tb('record')." where qid='{$qid}' and round='{$round}' order by createtime desc,msecond desc limit 1");
		if ($rcodes){
			$rcodes = explode(',', $rcodes);
			if (count($rcodes) == 1) $max = $rcodes[0];
			else $max = $rcodes[count($rcodes)-1];
		}
		for ($i = 0; $i < intval($amount/$cfg['creditnum']); $i++) {
			$mcodes[] = ++$max;
		}
		
		$this->memUpdateCredit($mem['openid'], -$amount);//粉丝中奖 增加奖励
		list($t1, $t2) = explode(' ', microtime());
		insert('record',array('qid'=>$qid,'mid'=>$mem['id'],'award'=>$amount,'createtime'=>$t2,'msecond'=>number_format($t1,6)*1000000,'codes'=>implode(',', $mcodes),'sel'=>$type,'round'=>$round,'type'=>$cid));
		
		$had = intval(col("select sum(award) from ".tb('record')." where qid='{$qid}' and round='{$round}'"));
		$last = $cate['credit'] - $had;
		if ($last <= 0){//足够了 开奖
			$rs = getall("select createtime,msecond from ".tb('record')." where qid='{$qid}' and round='{$round}' order by createtime desc,msecond desc limit 10");
			$all = 0;
			foreach ($rs as $value) {//最后10条时间相加
				$all += $value['createtime']*1000000 + $value['msecond'];
			}
			$acode = $all % $max;//除以最大夺金码 取余
			$mid = col("select mid from ".tb('record')." where qid='{$qid}' and round='{$round}' and find_in_set({$acode},codes) limit 1");
			//记录中奖记录
			insert('award',array('weid'=>$_W['uniacid'],'qid'=>$qid,'type'=>$cid,'round'=>$round,'code'=>$acode,'mid'=>$mid,'award'=>$cate['award'],'createtime'=>time()));
			$aopenid = col("select openid from ".tb('mem')." where id='{$mid}'");
			$this->memUpdateCredit($aopenid, $cate['award']);//粉丝中奖 增加奖励
			
			$data = array(
				'first'=>array('value'=>"恭喜您参与的【{$cfg['title']}】{$cate['title']}第{$round}期中奖了！"),
				'keyword1'=>array('value'=>$cate['award'].$cfg['creditname']),
				'keyword2'=>array('value'=>date('Y-m-d H:i:s')),
				'remark'=>array('value'=>'感谢你的参与，点击详情，再接再厉！'),
			);
			$this->sendTemplateMsg($aopenid, $cfg['awardmsg'], $data, $this->murl('cover'));
			
			//开启下一期
			if ($curRound['start'] + $question['hour'] * 3600 <= time()){//当前题目持续时间已过
				//看看有没下一题
				$mq = col("select id from ".tb('question')." where type='{$cid}' and weid='{$_W['uniacid']}' and isdel=0 and status=1 and id!='{$qid}' order by id limit 1");
				if (!empty($mq)){
					$qcon = ",qid=".$mq;
				}
			}
			$now = time();
			pdo_query("update ".tb('round')." set round=round+1,start={$now}{$qcon} where weid='{$_W['uniacid']}' and type='{$cid}'");
		}
		
		//任务奖励
		$now = time();
		$list = getall("select * from ".tb('task')." where starttime<=$now and endtime >$now and status=1 and type!=5");
		if ($list){
			$tasks = array();
			foreach ($list as &$v) {
				$task = array('tid'=>$v['id'],'award'=>$v['award'],'title'=>$v['title'],'level'=>0);
				if ($v['timetype']){//时间段任务  查询该时间段是否有完成的任务
					$con = " and createtime<={$v['endtime']} and createtime>={$v['starttime']}";
				}else {//每日任务
					$con = " and to_days(from_unixtime(createtime))=to_days(now())";
				}
				$r = getall("select level from ".tb('task_record')." where mid='{$mem['id']}' and tid='{$v['id']}' $con");
				$a = unserialize($v['award']);
				if ($r){//完成过任务
					if ($v['type'] == 1) continue;//若是首次夺金任务已玩过 则不奖励了
					elseif ($v['type'] == 2 || $v['type'] == 3){//若是夺金或连胜任务
						$l = 0;
						foreach ($r as $val) {
							$l = max($l,$val['level']);
						}
						if (count($r) == $l){//任务全完成了
							continue;
						}else{
							if ($v['type'] == 2) $num = intval(col("select count(1) from ".tb('record')." where mid='{$mem['id']}' {$con}"));
							elseif ($v['type'] == 3) $num = intval(col("select count(1) from ".tb('award')." where mid='{$mem['id']}' {$con}"));
							$has = 0;
							foreach ($a as $k => $value) {
								if ($num == $value['key'] && $k > $l){
									$task['award'] = $value['val'];
									$task['level'] = $k;
									$has = 1;
									break;
								}
							}
							if (!$has) continue;
						}
					}else{
						foreach ($r as $value) {
							$ls[] = $value['level'];
						}
						foreach ($a as $val) {
							if (!in_array($val['key'], $ls)) $cids[] = $val['key']; //该任务没领过的
						}
						if (in_array($cid+1, $cids)){
							$r = col("select count(1) from ".tb('record')." where mid='{$mem['id']}' and type='{$cid}' {$con}");
							if ($r == 1){//没玩过这个分场
								$has = 0;
								foreach ($a as $val) {
									if ($val['key'] == $cid+1){
										$task['award'] = $val['val'];
										$task['level'] = $val['key'];
										$has = 1;
										break;
									}
								}
								if (!$has) continue;
							}
						}else continue;
					}
				}elseif ($v['type'] > 1){
					if ($v['type'] == 2 || $v['type'] == 3){
						if ($v['type'] == 2) $num = intval(col("select count(1) from ".tb('record')." where mid='{$mem['id']}' {$con}"));
						elseif ($v['type'] == 3) $num = intval(col("select count(1) from ".tb('award')." where mid='{$mem['id']}' {$con}"));
						$has = 0;
						foreach ($a as $value) {
							if ($num == $value['key']){
								$task['award'] = $value['val'];
								$task['level'] = 0;
								$has = 1;
								break;
							}
						}
						if (!$has) continue;
					}else{
						$has = 0;
						foreach ($a as $val) {
							if ($val['key'] == $cid+1){
								$task['award'] = $val['val'];
								$task['level'] = $val['key'];
								$has = 1;
								break;
							}
						}
						if (!$has) continue;
					}
				}
				$tasks[] = $task;
			}
			if ($tasks){
				$str = '完成任务：';
				$all = 0;
				foreach ($tasks as $value) {
					insert('task_record',array('mid'=>$mem['id'],'tid'=>$value['tid'],'award'=>$value['award'],'createtime'=>time(),'level'=>$value['level']));
					$this->memUpdateCredit($mem['openid'], $value['award']);
					$all += $value['award'];
					$str .= "'{$value['title']}'";
				}
				$str .= "，奖励 {$all} ".$cfg['creditname'];
				resp(array('code'=>3,'msg'=>$str));
			}
		}
		
		resp(array('code'=>1));		
	}
	
	public function memUpdateCredit($openid,$award){
		$cfg = $this->module['config'];
		if ($cfg['credittype'] == 0){
			load()->model('mc');
			$m = mc_fetch($openid,array('uid'));
			mc_credit_update($m['uid'],'credit1',$award,array($m['uid'],'活动奖励'));
		}elseif ($cfg['credittype'] == 1){
			load()->model('mc');
			$m = mc_fetch($openid,array('uid'));
			mc_credit_update($m['uid'],'credit2',$award,array($m['uid'],'活动奖励'));
		}else{
			$fid = pdo_fetchcolumn("select id from ".tablename('junsion_account_fans')." where openid='{$openid}'");
			pdo_query('update '.tablename('junsion_account_fans')." set weibi=weibi+{$award} where id='{$fid}'");
			pdo_insert("junsion_account_weibi",array(
				'weid'=>$_W['uniacid'],
				'fans_weibi'=>pdo_fetchcolumn("select weibi from ".tablename('junsion_account_fans')." where id='{$fid}'"),
				'fid'=>$fid,
				'score'=>0,
				'money'=>0,
				'surplus'=>pdo_fetchcolumn('SELECT money FROM '.tablename('junsion_account_info').' WHERE weid=:weid',array(':weid'=>$_W['uniacid'])),
				'weibi'=>$award,
				'remark'=>$cfg['title'],
				'createtime'=>time()
			));
		}
	}
	
	public function sendTemplateMsg($openid,$msgid,$data,$url,$topcolor = '#FF0000'){
        global $_W;
        if ($url && stripos($url,'http://') === false){
            $url = $_W['siteroot'].str_replace('./','app/',$url);
        }
        load()->classs('weixin.account');
        $acid = pdo_fetchcolumn('select acid from '.tablename('account')." where uniacid={$_W['uniacid']}");
        $accObj = WeixinAccount::create($acid);
        return $accObj->sendTplNotice($openid,$msgid,$data,$url,$topcolor);
	}
	
	public function doWebList() {
		//这个操作被定义用来呈现 管理中心导航菜单
		global $_W,$_GPC;
		$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
		$cfg = $this->module['config'];
		if (empty($cfg['cates'])) MSG('请先设置夺金分场','./index.php?c=profile&a=module&do=setting&m=junsion_getscore');
		if('post' == $op){
			$id = intval($_GPC['id']);
			if(!empty($id)){
				//查找是否存在
				$item = get("SELECT * FROM ".tb('question')." WHERE id={$id}");
				if (empty($item)) {
					MSG('亲,数据不存在！', '', 'error');
				}
			}
			if(checksubmit('submit')){//检测是否post
				//验证
				if (empty($_GPC['title'])) {
					MSG('项目题目不能为空!');
				}
		
				$data = array(
					'weid'=>$_W['weid'],
					'title'=> $_GPC['title'],
					'type'=>$_GPC['type'],
					'status'=>$_GPC['status'],
					'yes_txt'=>$_GPC['yes_txt'],
					'yes_img'=>$_GPC['yes_img'],
					'no_txt'=>$_GPC['no_txt'],
					'no_img'=>$_GPC['no_img'],
					'hour'=>$_GPC['hour'],
				);
				if(empty($id)){
					insert('question', $data);//添加数据
					MSG('添加成功！', $this->wurl('list'));
				}else{
					update('question', $data, array('id' => $id));
					MSG('更新成功！', $this->wurl('list'));
				}
			}
			include $this->template('list');
		}else if('del' == $op){//删除数据
			$id = intval($_GPC['id']);
			$order = getall("SELECT id FROM ".tb('order')." WHERE pid='{$id}'");
			if (!empty($order)) update('question',array('isdel'=>1),array('id'=>$id));
			else del('question',array('id'=>$id));
			MSG('删除成功！', referer(), 'success');
		}else if('display'==$op){
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			$list = getall("SELECT * FROM ".tb('question')." WHERE weid = '{$_W['weid']}' and isdel=0 $condition  LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			foreach ($list as &$v) {
				$v['round'] = intval(col('select max(round) from '.tb('record')." where qid='{$v['id']}'"));
				$v['total'] = intval(col('select count(1) from '.tb('record')." where qid='{$v['id']}'"));
				$v['doing'] = intval(col('select round from '.tb('round')." where qid='{$v['id']}'"));
			}
			$total = col('SELECT COUNT(*) FROM ' . tb('question') . " WHERE weid = '{$_W['weid']}' and isdel=0 $condition");
			$pager = pagination($total, $pindex, $psize);
			include $this->template('list');
		}
	}
	
	public function doWebRecord(){
		global $_W,$_GPC;
		$cfg = $this->module['config'];
		$pindex = max(1, intval($_GPC['page']));
		$psize =20;//每页显示
		$qid = intval($_GPC['qid']);
		if ($qid) $condition = " WHERE qid = '{$qid}'";
		$mid = intval($_GPC['mid']);
		if ($mid) $condition = " WHERE mid = '{$mid}'";
		
		$list = getall("SELECT * FROM ".tb('record'). $condition ." order by createtime desc,msecond desc LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
		if ($list){
			
			foreach ($list as $value) {
				$pids[] = $value['qid'];
				$mids[] = $value['mid'];
			}
			
			$ps = getall("select id,title,yes_txt,no_txt from ".tb('question')." where id in (".implode(',', $pids).")",'id');
			$ms = getall("select id,nickname,avatar from ".tb('mem')." where id in (".implode(',', $mids).")",'id');
			
			foreach ($list as &$v) {
				$v['title'] = $ps[$v['qid']]['title'];
				$v['nickname'] = $ms[$v['mid']]['nickname'];
				$v['avatar'] = $ms[$v['mid']]['avatar'];
				$v['sel'] = $v['sel']?$ps[$v['qid']]['yes_txt']:$ps[$v['qid']]['no_txt'];
				$v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
			}
			
			$total = col('SELECT COUNT(*) FROM ' . tb('record') .$condition);
			$pager = pagination($total, $pindex, $psize);
		}
		
		include $this->template('record');
	}
	
	public function doWebOrder(){
		global $_W,$_GPC;
		$cfg = $this->module['config'];
		$pindex = max(1, intval($_GPC['page']));
		$psize =20;//每页显示
		$cid = intval($_GPC['cid']);
		$condition = " WHERE type = '{$cid}'";
		$mid = intval($_GPC['mid']);
		if ($mid) $condition = " WHERE mid = '{$mid}'";
	
		$list = getall("SELECT * FROM ".tb('award'). $condition ." order by round desc LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
		if ($list){
				
			foreach ($list as $value) {
				$pids[] = $value['qid'];
				$mids[] = $value['mid'];
			}
				
			$ps = getall("select id,title from ".tb('question')." where id in (".implode(',', $pids).")",'id');
			$ms = getall("select id,nickname,avatar from ".tb('mem')." where id in (".implode(',', $mids).")",'id');
				
			foreach ($list as &$v) {
				$v['title'] = $ps[$v['qid']]['title'];
				$v['nickname'] = $ms[$v['mid']]['nickname'];
				$v['avatar'] = $ms[$v['mid']]['avatar'];
			}
				
			$total = col('SELECT COUNT(*) FROM ' . tb('award') .$condition);
			$pager = pagination($total, $pindex, $psize);
		}
	
		include $this->template('order');
	}
	
	public function doWebMem(){
		global $_W,$_GPC;
		$pindex = max(1, intval($_GPC['page']));
		$psize =20;//每页显示
		$list = getall("SELECT * FROM ".tb('mem')." WHERE weid = '{$_W['weid']}' LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
		load()->model('mc');
		foreach ($list as &$v) {
			$m = mc_fetch($v['openid'],array('credit1','credit2','mobile'));
			$v['credit1'] = $m['credit1'];
			$v['credit2'] = $m['credit2'];
			$v['mobile'] = $m['mobile'];
			$v['count'] = intval(col("select count(1) from ".tb('record')." where mid='{$v['id']}'"));
			$v['award'] = intval(col("select count(1) from ".tb('award')." where mid='{$v['id']}'"));
		}
		$total = col('SELECT COUNT(*) FROM ' . tb('mem') . " WHERE weid = '{$_W['weid']}' ");
		$pager = pagination($total, $pindex, $psize);
		include $this->template('mem');
	}
	
	public $TASK = array(
		1=>'首次夺金奖励',
		2=>'夺金次数奖励',
		3=>'中奖奖励',
		4=>'参与指定夺金项目奖励',
		5=>'外链任务',
	);
	public function doWebTask() {
		//这个操作被定义用来呈现 管理中心导航菜单
		global $_W,$_GPC;
		$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
		if('post' == $op){
			$id = intval($_GPC['id']);
			if(!empty($id)){
				//查找是否存在
				$item = get("SELECT * FROM ".tb('task')." WHERE id={$id}");
				if (empty($item)) {
					MSG('亲,数据不存在！', '', 'error');
				}
				$date = array('start'=>date('Y-m-d H:i:s',$item['starttime']),'end'=>date('Y-m-d H:i:s',$item['endtime']));
				if ($item['type'] > 1 && $item['type'] != 5) $item['award'] = unserialize($item['award']);
			}
			if(checksubmit('submit')){//检测是否post
				//验证
				if (empty($_GPC['title'])) {
					MSG('项目题目不能为空!');
				}
				
				$data = array(
					'weid'=>$_W['weid'],
					'title'=> $_GPC['title'],
					'award'=> $_GPC['award'],
					'type'=> $_GPC['type'],
					'timetype'=> $_GPC['timetype'],
					'starttime'=> strtotime($_GPC['date']['start']),
					'endtime'=> strtotime($_GPC['date']['end']),
					'status'=> $_GPC['status'],
					'logo'=> $_GPC['logo'],
					'des'=> $_GPC['des'],
					'sort'=> $_GPC['sort'],
				);
				
				if ($data['type'] > 1){
					if ($data['type'] == 5){
						$data['award'] = $_GPC['url'];
					}else{
						foreach ($_GPC['val'] as $k => $value) {
							if (!empty($value)) $award[] = array('val'=>$value,'key'=>$_GPC['key'][$k],'desc'=>$_GPC['desc'][$k]);
						}
						$data['award'] = serialize($award);
					}
				}
				
				if(empty($id)){
					insert('task', $data);//添加数据
					MSG('添加成功！', $this->wurl('task'));
				}else{
					update('task', $data, array('id' => $id));
					MSG('更新成功！', $this->wurl('task'));
				}
			}
			$cates = $this->module['config']['cates'];
			include $this->template('task');
		}else if('del' == $op){//删除数据
			$id = intval($_GPC['id']);
			del('task',array('id'=>$id));
			MSG('删除成功！', referer(), 'success');
		}else if('display'==$op){
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			$task = getall("SELECT * FROM ".tb('task')." WHERE weid = '{$_W['weid']}' $condition order by sort desc  LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$cates = $this->module['config']['cates'];
			foreach ($task as &$value) {
				if ($value['type'] > 1){
					if ($value['type'] == 5) $value['award'] = "<a target='_blank' href='{$value['award']}'>外链任务</a>";
					else{
						$award = unserialize($value['award']);
						$value['award'] = '';
						foreach ($award as $v) {
							if ($value['type'] == 2) $value['award'] .= "夺金 ".$v['key']." 次，奖励 ".$v['val']."<br>";
							elseif ($value['type'] == 3) $value['award'] .= "连胜 ".$v['key']." 次，奖励 ".$v['val']."<br>";
							elseif ($value['type'] == 4) $value['award'] .= "参与 ".$cates[$v['key']-1]['title']."，奖励 ".$v['val']."<br>";
						}
					}
				}
				$value['count'] = intval(col("select count(1) from ".tb('task_record')." where tid='{$value['id']}'"));
			}
			$total = col('SELECT COUNT(*) FROM ' . tb('task') . " WHERE weid = '{$_W['weid']}'  $condition");
			$pager = pagination($total, $pindex, $psize);
			include $this->template('task');
		}
	}
	
	
	public function getMem(){
		global $_W,$_GPC;
		$mem = get('select * from '.tb('mem')." where openid='{$_W['openid']}' and weid='{$_W['uniacid']}'");
		if (empty($mem)){
			$fans = $_W['fans'];
			if (!$fans['nickname']){
				load()->model('mc');
				$fans = mc_oauth_userinfo();
				$fans['avatar'] = $fans['headimgurl'];
			}else $fans['avatar'] = $fans['tag']['avatar'];
			$mem = array('weid'=>$_W['uniacid'],'nickname'=>$fans['nickname'],'avatar'=>$fans['avatar'],'openid'=>$fans['openid'],'createtime'=>time());
			insert('mem',$mem);
			$mem['id'] = pdo_insertid();
		}
		$cfg = $this->module['config'];
		$mem['credittype'] = $cfg['credittype'];
		if ($cfg['credittype'] == 0){
			$mem['creditname'] = '积分';
			load()->model('mc');
			$m = mc_fetch($mem['openid'],array('credit1'));
			$mem['credit'] = intval($m['credit1']);
		}elseif ($cfg['credittype'] == 1){
			$mem['creditname'] = '余额';
			load()->model('mc');
			$m = mc_fetch($mem['openid'],array('credit2'));
			$mem['credit'] = $m['credit2'];
		}else{
			$mem['credit'] = intval(col("select weibi from ".tablename('junsion_account_fans')." where openid='{$mem['openid']}'"));
		}
		return $mem;	
	}
	

	public function wurl($action,$params = array()){
		return $this->createWebUrl($action, $params);
	}
	
	public function murl($action,$params = array()){
		return $this->createMobileUrl($action, $params);
	}
}
function MSG($text,$url = '',$status = ''){
	message($text,$url,$status);
}
function resp($data){
	die(json_encode($data,JSON_UNESCAPED_UNICODE));
}
function tb($name){
	return tablename('junsion_getscore_'.$name);
}
function update($name,$arr = '',$arr2 = ''){
	return pdo_update('junsion_getscore_'.$name,$arr,$arr2);
}
function insert($name,$arr = ''){
	return pdo_insert('junsion_getscore_'.$name,$arr);
}
function del($name,$arr = '',$op = 'and'){
	return pdo_delete('junsion_getscore_'.$name,$arr,$op);
}
function get($sql){
	return pdo_fetch($sql);
}
function col($sql){
	return pdo_fetchcolumn($sql);
}
function getall($sql,$col = ''){
	if ($col) return pdo_fetchall($sql,array(),$col);
	return pdo_fetchall($sql);
}